<?php
class ProfilesController extends AppController {
	var $name = 'Profiles';
	var $helpers = array('Html','Form');
	var $uses = array('Organization', 'Profile');
    
    function index() {
       $this->redirect('/profiles/view/');
    }
    
    function edit() {
        $title = 'Editar Perfil';
        $this->set('title', $title);
        $this->set('pageTitle', $title);
        
        $organization=$this->othAuth->getData('organization');
        $organization = $this->Organization->find(array('Organization.id' => $organization['id']));
        
        $id=$organization['Organization']['profile_id']; 
        $this->Profile->id = $id;
        if (empty($this->data)) {
			$this->data = $this->Profile->read();
		} else {
    		$profile = $this->Profile->find(array('Organization.id' => $organization['Organization']['id']));

    		if (isset($profile['Profile']['id']) && (!empty($profile['Profile']['id']))) {
    			$this->data['Profile']['id'] = $profile['Profile']['id'];
    		}

    		if ($this->Profile->save($this->data)) {
    			if ((!isset($this->data['Profile']['id'])) || (empty($this->data['Profile']['id']))) {
    				$profile_id = $this->Profile->getLastInsertId();
    				$this->data['Organization']['id'] = $organization['Organization']['id'];
    				$this->data['Organization']['profile_id'] = $profile_id;
    			}

    			if ($this->Organization->save($this->data)) {
    				$_SESSION['mensagem']['success'][] = 'Perfil cadastrada com sucesso!';
    			} else {
    				$_SESSION['mensagem']['error'][] = 'Erro ao tentar cadastrar Perfil.';
    			}
    		} else {
    			$_SESSION['mensagem']['error'][] = 'Erro ao tentar cadastrar Perfil.';
    		}
    		$this->redirect('/profiles/edit/');
		}
        
        $profile = $this->Profile->find(array('Profile.id' => $id));
        $this->set('profile',$profile);  
        
    }
}

